package com.liuhengjia.controller;

import com.liuhengjia.pojo.Result;
import com.liuhengjia.pojo.User;
import com.liuhengjia.service.UserService;
import com.liuhengjia.util.Jwts;
import com.liuhengjia.util.Md5s;
import com.liuhengjia.util.ThreadLocals;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 注册
     *
     * @param username 用户名
     * @param password 密码
     * @return com.liuhengjia.pojo.Result
     */
    @PostMapping("/register")
    public Result<Object> register(@Pattern(regexp = "^\\S{5,16}$", message = "用户名必须为 5~16 位非空字符，不能包含空格") String username,
                                   @Pattern(regexp = "^\\S{5,16}$", message = "密码必须为 5~16 位非空字符，不能包含空格") String password) {
        // 查询用户
        User user = userService.selectByUsername(username);
        if (user != null) {
            // 存在，提醒用户
            return Result.error("用户名已被占用");
        }
        // 注册
        userService.register(username, password);
        return Result.success();
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return com.liuhengjia.pojo.Result
     */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$", message = "用户名必须为 5~16 位非空字符，不能包含空格") String username,
                                @Pattern(regexp = "^\\S{5,16}$", message = "密码必须为 5~16 位非空字符，不能包含空格") String password) {
        User user = userService.selectByUsername(username);
        if (user == null) {
            return Result.error("用户不存在，请先注册");
        }
        if (!Md5s.checkPassword(password, user.getPassword())) {
            return Result.error("密码错误");
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUsername());
        String jwtStr = Jwts.genToken(claims);
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(jwtStr, jwtStr, 12, TimeUnit.HOURS);
        return Result.success(jwtStr);
    }

    /**
     * 获取用户信息
     *
     * @return com.liuhengjia.pojo.Result<User>
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        /*Map<String, Object> decodeMap = Jwts.parseToken(token);
        String username = (String) decodeMap.get("username");*/
        Map<String, Object> decodeMap = ThreadLocals.get();
        return Result.success(userService.selectByUsername((String) decodeMap.get("username")));
    }

    /**
     * 更新用户基本信息
     *
     * @param user 用户
     * @return com.liuhengjia.pojo.Result<Object>
     */
    @PutMapping("/update")
    public Result<Object> update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    /**
     * 更新用户头像
     *
     * @param avatarUrl 图像路径
     */
    @PatchMapping("/updateAvatar")
    public Result<Object> updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 更新用户密码
     *
     * @param params Map<String, String>
     * @return com.liuhengjia.pojo.Result<Object>
     */
    @PatchMapping("/updatePwd")
    public Result<Object> updatePwd(@RequestBody Map<String, String> params,
                                    @RequestHeader("Authorization") String token) {
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }
        if (oldPwd.equals(newPwd)) {
            return Result.error("新旧密码一样");
        }
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次填写的新密码不一样");
        }

        Map<String, Object> decodeMap = ThreadLocals.get();
        String username = (String) decodeMap.get("username");
        User user = userService.selectByUsername(username);
        if (!Md5s.checkPassword(oldPwd, user.getPassword())) {
            return Result.error("原密码填写不正确");
        }
        userService.updatePwd(newPwd);
        redisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }

}
